package cn.llming.gift.exception.handle;

import cn.llming.gift.exception.ErrorCode;
import cn.llming.gift.exception.LlmingException;
import cn.llming.gift.util.AjaxResult;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

@RestControllerAdvice //可以在controller执行前，后做一些事情
public class GlobalExceptionHandler {


    @ExceptionHandler(LlmingException.class)   //处理业务异常
    public AjaxResult globalExceptionHandler(LlmingException e){
        e.printStackTrace();
        return AjaxResult.me().setSuccess(false).setCode(e.getCode()).setMessage(e.getMessage());
    }
    @ExceptionHandler(MethodArgumentNotValidException.class)   //处理业务异常
    public AjaxResult methodArgumentNotValidException(MethodArgumentNotValidException e){
        e.printStackTrace();
        BindingResult bindingResult = e.getBindingResult(); //获取bindingResult
        //获取所有的字段错误
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        //拼接每个字段错误的提示信息,中间用逗号分隔
        StringBuilder sb = new StringBuilder();
        fieldErrors.forEach(fieldError -> {
            sb.append(fieldError.getDefaultMessage()+",");
        });
        String message = sb.substring(0,sb.length()-1); //去除最后一个逗号
        return AjaxResult.me().setSuccess(false).setCode(ErrorCode.CODE_400.getCode()).setMessage(message);
    }

    @ExceptionHandler(Exception.class)   //处理未知异常
    public AjaxResult exceptionHandler(Exception e){

        return AjaxResult.me().setSuccess(false).setCode(ErrorCode.CODE_500.getCode()).setMessage("系统繁忙，请稍后重试");
    }
}